package edu.ucdavis.gwt.gis.client.query;


import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;

import edu.ucdavis.cstars.client.MapWidget;
import edu.ucdavis.cstars.client.event.MapPanEndHandler;
import edu.ucdavis.cstars.client.event.MapZoomEndHandler;
import edu.ucdavis.cstars.client.geometry.Extent;
import edu.ucdavis.cstars.client.geometry.Point;
import edu.ucdavis.gwt.gis.client.DataManager;
import edu.ucdavis.gwt.gis.client.GisClient;

public class PointSelectPanel extends HTML {
	
	private Point p = null;
	private MapWidget map = null;
	
	public PointSelectPanel() {
		setHTML("&nbsp;");
	}

	public void setMap(MapWidget map) {
		this.map = map;
		map.addPanEndHandler(new MapPanEndHandler() {
			@Override
			public void onMapPanEnd(Extent extent, Point endPoint) {
				if( isAttached() ) updatePosition();
			}
		});
		map.addZoomEndHandler(new MapZoomEndHandler() {
			@Override
			public void onZoomEnd(Extent extent, float zoomFactor,
					Point anchor, int level) {
				if( isAttached() ) updatePosition();
			}
		});
	}
	
	private void updatePosition() {
		Point sp = map.toScreen(p);
		GisClient client = DataManager.INSTANCE.getClient();
		getElement().getStyle().setLeft(client.getLeft()+sp.getX()-5, Unit.PX);
		getElement().getStyle().setTop(client.getTop()+sp.getY()-5, Unit.PX);
	}
	
	public void show(Point p) {
		this.p = p;
		animateBig.cancel();
		animateSmall.cancel();
		
		setStyleName("PointSelectPanel-small");
		updatePosition();
		
		RootPanel.get().add(this);
		
		animateBig.schedule(50);
	}

	
	private Timer animateBig = new Timer() {
		@Override
		public void run() {
			setStyleName("PointSelectPanel-big");
			animateSmall.schedule(750);
		}
	};
	
	private Timer animateSmall = new Timer() {
		@Override
		public void run() {
			setStyleName("PointSelectPanel-small");
			animateBig.schedule(750);
		}
	};
	
	public void hide() {
		animateBig.cancel();
		animateSmall.cancel();
		RootPanel.get().remove(PointSelectPanel.this);
	}
	
}
